package com.tju.serviceUcenter.controller;

import com.google.gson.Gson;
import com.tju.JwtUtils;
import com.tju.Result;
import com.tju.serviceHandler.GuliException;
import com.tju.serviceUcenter.entity.UcenterMember;
import com.tju.serviceUcenter.service.UcenterMemberService;
import com.tju.serviceUcenter.utils.ConstantWxUtils;
import com.tju.serviceUcenter.utils.HttpClientUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;


import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;

@Controller
@RequestMapping("/educenter/wx")
@CrossOrigin
public class WxApiController {

    @Autowired
    private UcenterMemberService memberService;


    //生成微信扫描的二维码
    @GetMapping("login")
    public String getWxCode(){
        String baseUrl ="https://open.weixin.qq.com/connect/qrconnect"
                +"?appid=%s"
                +"&redirect_uri=%s"
                +"&response_type=code"
                +"&scope=snsapi_login"
                +"&state=%s"
                +"#wechat_redirect";
        String redirect_uri = ConstantWxUtils.WX_REDIRECT_URL;
        try {
            URLEncoder.encode(redirect_uri,"utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String url = String.format(baseUrl,
                ConstantWxUtils.WX_APP_ID,
                redirect_uri,
                "gsc");
        return "redirect:" + url;
    }

    @GetMapping("callback")
    public String callback(String code,String state){
        //类似于验证码，每次都是随机生成的唯一值
        //根据得到的code请求微信提供的固定地址，
        // 获取 access_token访问凭证 和 openid 每个微信的唯一标识
        //拿到那两个值之后再去请求固定的地址
        //拿着code，去请求微信固定的地址，得到两个值 access_token 和 openid
        String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token"+
                "?appid=%s" +
                "&secret=%s" +
                "&code=%s" +
                "&grant_type=authorization_code";

        //拼接三个参数：id 秘钥 和 code值
        String accessTokenUrl = String.format(baseAccessTokenUrl,
                ConstantWxUtils.WX_APP_ID
                , ConstantWxUtils.WX_APP_SECRET
                , code);
        //请求拼接好的地址，返回access_token，和ipenid
        try {
            String accessTokenInfo = HttpClientUtils.get(accessTokenUrl);
            System.out.println("accessTokenInfo "  + accessTokenInfo);
            //从accessTokenInfo中取出access_token 和 openid  字符串转为map
            Gson gson = new Gson();
            HashMap map = gson.fromJson(accessTokenInfo, HashMap.class);
            String access_token = (String) map.get("access_token");
            String openid = (String) map.get("openid");

            //根据openid来查询是否已经存在数据库中
            UcenterMember member = memberService.getOpenIdMember(openid);
            if (member == null){
                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";
                String userInfoUrl = String.format(baseUserInfoUrl,
                        access_token, openid);
                String userInfo = HttpClientUtils.get(userInfoUrl);
                System.out.println("userInfo" + userInfo);
                //获取扫码人信息  昵称和头像  帮助用户注册信息
                HashMap userInfoMap = gson.fromJson(userInfo, HashMap.class);
                String nickname = (String) userInfoMap.get("nickname");
                String headimgurl = (String) userInfoMap.get("headimgurl");
                //进行添加
                member = new UcenterMember();
                member.setOpenid(openid);
                member.setNickname(nickname);
                member.setAvatar(headimgurl);
                memberService.save(member);
            }
            //使用jwt根据member对象生成token字符串
            String token = JwtUtils.getJwtToken(member.getId(), member.getNickname());

            return "redirect:http://localhost:3000?token=" + token;

        } catch (Exception e) {
            throw new GuliException(20001,"扫码登录失败!");
        }

    }
}
